package org.apache.i18n.translater.google;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.i18n.translater.PowerTranslater;
import org.apache.i18n.translater.Translater;

import com.google.api.translate.Language;
import com.google.api.translate.Translate;

public class GoogleTranslater extends Translater {

	static private Log log= LogFactory.getLog(GoogleTranslater.class);
	public GoogleTranslater() {
		Translate.setHttpReferrer("http://harmony-i18n-tool.googlecode.org");
	}

	@Override
	public String translateSentence(String from) {

		String fromChanged=before(from);
		try {
			String to = Translate.execute(fromChanged, Language.ENGLISH,
					Language.CHINESE);
			return after(to);
		} catch (Exception e) {
			log.warn("不能翻译:" + from, e);
			return from; //出现错误不翻译
		}

	}

	 String before(String from) {
		from =StringUtils.replace(from, "{0}", "___0___");
		from =StringUtils.replace(from, "{1}", "___1___");
		from =StringUtils.replace(from, "{2}", "___2___");
		from =StringUtils.replace(from, "{3}", "___3___");

		return from;
	}

	 String after(String from) {
		from =StringUtils.replace(from, "___0___", "{0}");
		from =StringUtils.replace(from, "___1___", "{1}");
		from =StringUtils.replace(from, "___ 1___", "{1}");
		
		from =StringUtils.replace(from, "___2___", "{2}");
		from =StringUtils.replace(from, "___3___", "{3}");
		
		return from;
	}

}
